'use strict'

const fs = require('fs');
const path = require('path')
const router = require('koa-router')();

function foreachControllers(dir){

    let files = fs.readdirSync(dir);
    let controllerFiles = files.filter((name)=>{

        return name.endsWith('js') && name !=='index.js'
    })
    return controllerFiles;
}

function registerRouter(files){
files.forEach(element => {
    let tmpFile = path.join(__dirname,element);
    let tmpRoutes = require(tmpFile);
    for (const key in tmpRoutes) {
       console.log(key);
       let type = tmpRoutes[key][0];
       let fn = tmpRoutes[key][1]
       if(type === 'get'){
           router.get(key,fn)
       }else{
           router.post(key,fn)
       }
    }
    
});
}

module.exports=function(){

    const dir = __dirname;
    const controllerFiles = foreachControllers(dir)
    registerRouter(controllerFiles);
    return router.routes();
}